package oldreturn

import (
	"errors"
	"fmt"

	"oldReturn/src/tools/cache"

	"time"
)

type UserParam struct {
	UserId    string `json:"UserId" binding:"required"`
	PartnerId int    `json:"PartnerId" binding:"required"`
}

func CheckUserIsOld(user UserParam) (bool, int, error) {

	User, err := UserCache(user)
	if err != nil {
		return false, 0, err
	}
	UserInfo := User.(UserInfo)

	if UserInfo.LoginTime == "" {
		return false, UserInfo.IsJoin, nil
	}

	day30Ago := time.Now().AddDate(0, -1, 0)
	LoginTime, err := time.ParseInLocation("2006-01-02 15:04:05", UserInfo.LoginTime, time.Local)
	if err != nil {
		fmt.Println(err)
		return false, UserInfo.IsJoin, err
	}
	if !LoginTime.Before(day30Ago) {
		return false, UserInfo.IsJoin, err
	} else {
		return true, UserInfo.IsJoin, err
	}
}

func UserCache(user UserParam) (interface{}, error) {
	ca := cache.GetCacheManager()
	User, ok := ca.C.Get(user.UserId)
	if !ok {
		user, err := QueryUser(user.UserId, user.PartnerId)
		if err != nil {
			return user, err
		}
		if user.UserId == "" {
			return user, errors.New("用户不存在！")
		}
		ca.C.Set(user.UserId, user, 0)
		return user, nil
	}
	return User, nil
}
